/**
 * File    : CustomValidationDecorator.java
 * Created : 2008-10-18
 * By      : LuHuiguo
 */
package com.luhuiguo.tapestry;

import org.apache.tapestry5.BaseValidationDecorator;
import org.apache.tapestry5.CSSClassConstants;
import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationTracker;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.services.Environment;
import org.apache.tapestry5.services.FormSupport;

/**
 * @author LuHuiguo
 * @version $Id: CustomValidationDecorator.java 15 2008-10-18 15:58:23Z LuHuiguo $
 * 
 */
public class CustomValidationDecorator extends BaseValidationDecorator {
	private final Environment environment;

	private final MarkupWriter markupWriter;

	public CustomValidationDecorator(Environment environment,
			MarkupWriter markupWriter) {
		this.environment = environment;
		this.markupWriter = markupWriter;
	}

	@Override
	public void insideField(Field field) {
		if (inError(field))
			addErrorClassToCurrentElement();
	}

	@Override
	public void insideLabel(Field field, Element element) {
		if (field == null)
			return;

		if (inError(field))
			element.addClassName(CSSClassConstants.ERROR);
	}

	@Override
	public void afterField(Field field) {
		// boolean inError = inError(field);
		//
		// boolean clientValidationEnabled = getFormSupport()
		// .isClientValidationEnabled();
		//
		// if (inError || clientValidationEnabled) {
		// String iconId = field.getClientId() + ":icon";
		//
		// String cssClass = inError ? "t-error-icon"
		// : "t-error-icon t-invisible";
		// markupWriter.element("img", "src", spacerAsset.toClientURL(),
		// "alt", "", "class", cssClass, "id", iconId);
		// markupWriter.end();
		// }

	}

	@SuppressWarnings("unused")
	private FormSupport getFormSupport() {
		return environment.peekRequired(FormSupport.class);
	}

	private boolean inError(Field field) {
		ValidationTracker tracker = environment
				.peekRequired(ValidationTracker.class);

		return tracker.inError(field);
	}

	private void addErrorClassToCurrentElement() {
		markupWriter.getElement().addClassName(CSSClassConstants.ERROR);
	}
}
